package com.lkl.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lkl.bean.*;
import com.lkl.client.OrderClients;
import com.lkl.client.PayClients;
import com.lkl.client.TicketClients;
import com.lkl.service.ChangeOrderService;
import com.lkl.utils.GenerateOrderNum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lkl
 * @Description
 * @Date 2022/3/28
 */
@Service
public class ChangeOrderServiceImpl implements ChangeOrderService {

    @Autowired
    OrderClients orderClients;

    @Autowired
    TicketClients ticketClients;

    @Autowired
    PayClients payClients;

    static final Logger logger = LoggerFactory.getLogger(ChangeOrderServiceImpl.class);


    @Override
    @Transactional
    public BaseResp updateById(BaseReq baseReq) {

        String orderId = baseReq.getOrderId();

        if (orderId == null) {
            return new BaseResp(0, "请选择订单", null, null);
        }
        //远程调用到order中先查到票的数据，判断票是否有位置
        BaseResp byId = orderClients.findByOrderid(orderId);

        if (byId.getCode() == 0) {
            return new BaseResp(0, "查询不到此订单~", null, null);
        }
        Object data = byId.getData();
        String string = JSONObject.toJSONString(data);
        TgOrder tgOrder = JSONObject.parseObject(string, TgOrder.class);
        //找到这个订单以后先把价格记录一下
        Double oldPrice = tgOrder.getOrderPrice();

        //开始改签 ，查一下这个车次还有没有座位；
        BaseResp ticketClientsById = ticketClients.findById(Integer.valueOf(baseReq.getDetailId()));

        if (ticketClientsById.getCode() == 0) {
            return new BaseResp(0, "座位无票~", null, null);
        }

        //找到票的价格
        Object data1 = ticketClientsById.getData();
        String string1 = JSONObject.toJSONString(data1);
        Ticket ticket = JSONObject.parseObject(string1, Ticket.class);
        System.out.println(ticket);

        Double superSeatPrice = 0.0;
        Double firstSeatPrice = 0.0;
        Double secondSeatPrice = 0.0;

        //获取后台价格
        Integer check = baseReq.getCheck();
        if(check==1){
            superSeatPrice = ticket.getMessage().getSuperSeatPrice();
            if(superSeatPrice==null){
                return new BaseResp(0,"价格为空！",null,null);
            }
        }else if(check==2){
            //价格记录一下
            firstSeatPrice = ticket.getMessage().getFirstSeatPrice();
            if(firstSeatPrice==null){
                return new BaseResp(0,"价格为空！",null,null);
            }
        }else {

            secondSeatPrice = ticket.getMessage().getSecondSeatPrice();
            if(secondSeatPrice==null){
                return new BaseResp(0,"价格为空！",null,null);
            }
        }

        BaseResp detailByOrderid = orderClients.findDetailByOrderid(orderId);

        if (detailByOrderid.getCode() == 0) {
            return new BaseResp(0, "查不到车票信息~", null, null);
        }

        Object data2 = detailByOrderid.getData();
        String string2 = JSONObject.toJSONString(data2);
        List tgOrderDetails = JSONObject.parseObject(string2, List.class);

        //这里是随便找一个detailId来给支付
        Object o = tgOrderDetails.get(0);
        String string3 = JSONObject.toJSONString(o);
        TgOrderDetail tgOrderDetail = JSONObject.parseObject(string3, TgOrderDetail.class);

        String orderDetailId = tgOrderDetail.getOrderDetailId();

        System.out.println(tgOrderDetails);

        //找到数量
        int size = tgOrderDetails.size();

        Double newPrice = 0.0;

        //如果改签的是特等座
        if (baseReq.getCheck() == 1) {
            newPrice = superSeatPrice * size;
        }
        if (baseReq.getCheck() == 2) {
            newPrice = firstSeatPrice * size;
        }
        if (baseReq.getCheck() == 3) {
            newPrice = secondSeatPrice * size;
        }

        //开始支付改签所需价格
        if (newPrice < oldPrice) {

            String oldOrderId = tgOrder.getOrderId();

            //改签以后要修改订单信息
            tgOrder.setOrderPrice(newPrice);
            tgOrder.setTicketId(ticket.getId());
            tgOrder.setUpdateTime(new Date());

            //生成新id
            String newId = new GenerateOrderNum().generate("");

            tgOrder.setOrderId(newId);

            //退还金额
            Map map = new HashMap();
            map.put("orderDetailId", orderDetailId);
            map.put("price", oldPrice - newPrice);

            System.out.println(tgOrder);

            //增加一个新的订单，删除原来的订单
            orderClients.saveAndFlush(tgOrder);
            orderClients.delById(oldOrderId);

            logger.debug("订单已经改签成功!{}");
            System.out.println("订单已经改签成功");
            BaseResp baseResp = payClients.refundTicket(map);

            baseResp.setMassage("订单已经改签成功,开始退款！");

            return baseResp;

        } else if (newPrice > oldPrice) {
            String oldOrderId = tgOrder.getOrderId();
            //支付剩余金额
            //改签以后要修改订单信息
            tgOrder.setOrderPrice(newPrice);
            tgOrder.setTicketId(ticket.getId());
            tgOrder.setUpdateTime(new Date());

            tgOrder.setOrderId(new GenerateOrderNum().generate(""));

            Map map = new HashMap();
            map.put("orderId", tgOrder.getOrderId());
            map.put("price", oldPrice - newPrice);

            //增加一个新的订单，删除原来的订单
            orderClients.saveAndFlush(tgOrder);
            orderClients.delById(oldOrderId);

            logger.debug("订单已经改签成功!{}");
            System.out.println("订单已经改签成功");
            BaseResp baseResp = payClients.buyTicket(map);
            baseResp.setMassage("订单已经改签成功,开始支付！");

            return baseResp;

        }else {

            String oldOrderId = tgOrder.getOrderId();

            //价格一样的时候 ，就直接存进去
            tgOrder.setOrderPrice(newPrice);
            tgOrder.setTicketId(ticket.getId());
            tgOrder.setUpdateTime(new Date());

            //生成新id
            String newOrderId = new GenerateOrderNum().generate("");

            tgOrder.setOrderId(newOrderId);
            tgOrder.setOrderStatus(2);

            BaseResp baseResp1 = orderClients.saveAndFlush(tgOrder);
            orderClients.delById(oldOrderId);
            System.out.println("改签结果：" + baseResp1);
            logger.debug("订单已经改签成功!{}");

            //修改detail的orderId
            for (Object orderDetail : tgOrderDetails) {
                String string4 = JSONObject.toJSONString(orderDetail);
                TgOrderDetail tgOrderDetail1 = JSONObject.parseObject(string4, TgOrderDetail.class);
                tgOrderDetail1.setOrderId(newOrderId);
                orderClients.updateOrderId(tgOrderDetail1);
            }

            return new BaseResp(1, "改签成功！", null, null);

        }

    }
}
